<?php

namespace App\Service\OrderService\OrderRouteService;

use App\Service\Code\Normal;
use Service\AppService\IdService;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Model\CommodityModel\SupplierCommodity;
use App\Model\PssModel\OrderSupplier;
use App\Service\VendorClient\ShopjdApi\ShopjdkeplerClient;
use App\Service\AppService\SystemCacheConfigService;

/**
 * 京东开普勒云交易系统供应商对接
 * 电商平台负责申报支付单，供应商申报订单和清单
 * @author hj
 */
class Shopjdkepler extends BaseSupplierRouterService 
{
    /**
     * 创建订单
     * @param array $param
     * @return array
     */
    public function createOrder($param = []) {
        //下单商品重组
        $supplierGoodsInfo = $param['supplierGoodsInfo'];
        $userGoodsList     = $supplierGoodsInfo['userGoodsList'];
        $goodsList         = $supplierGoodsInfo['goodsList'];
        $orderItems        = [];
        $supplierCode      = $supplierGoodsInfo['supplierCode'];
        //按照仓区进行拆单 目前就一个仓库 不排除后面会有其它仓库
        $defaultStockGroupGoodsList = [];
        foreach ($goodsList as $item) {
            $defaultStockGroupGoodsList[$item['defaultStock']][] = $item;
            unset($item);
        }

        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
        ) ? true : false;
        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false;

        foreach ($defaultStockGroupGoodsList as $item) 
        {
            $currentGoods          = current($item);
            $supplierCommodityType = $currentGoods['supplierCommodityType'];

            //重新合并每一个仓库商品
            $orderGoods = [];
            foreach ($item as $goods) {
                $orderGoods = array_merge($orderGoods, $userGoodsList[$goods['skuCode']]);
                unset($goods);
            }

            //生成供应商主单号
            $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
            $param['order']['supplier_csn'] = IdService::instance()->getOtherID();

            //防止订单号重复问题,下游已申报，则使用下游的订单号作为中台子单号
            if ($isDelare && !$isShop && $supplierCommodityType != GOODS_TYPE_YBMY) {
                $param['order']['supplier_dsn'] = $param['order']['orderSn'];
            } else {
                
                //$param['order']['supplier_dsn'] = IdService::instance()->getOtherID();兼容百大老系统，等bbc新系统上线之后，改切换到云仓自己的订单号
                $param['order']['supplier_dsn'] = $param['order']['orderSn'];
            }

            $param['order']['goods']          = $orderGoods;
            $param['order']['isQueryExpress'] = 1;
            $res                              = OrderSupplier::instance()->getSupplierCreateOrderData($param);
            if ($res['code'] != Normal::SUC) {
                return $res;
            }
            $orderItems[] = $res['data'];
        }

        return Normal::returnCode(Normal::SUC, "获取成功", [
            'supplierCode' => $supplierCode,
            'orderItems'   => $orderItems
        ]);
    }

    /**
     * 订单支付
     * @param array $param
     * @return array
     */
    public function orderPay($param = []) {
        $goodsList      = $param['orderGoods'];
        $supplierSkuIds = array_column($goodsList, 'supplier_skuid');
        $goodsIdArr     = SupplierCommodity::whereIn('ID', $supplierSkuIds)->pluck('SupplierCommodityKey', 'ID')->toArray();
        foreach ($param['orderGoods'] as &$item) {
            if (isset($goodsIdArr[$item['supplier_skuid']])) {
                $item['supplier_commodity_key'] = $goodsIdArr[$item['supplier_skuid']];
            }
            unset($item);
        }
        return $this->callSdkApi(ShopjdkeplerClient::class, $param['apiBody'])->createOrder($param);
    }

    /**
     * 订单取消
     * @param array $param
     * @return array
     */
    public function orderCancel($param = []) {
        return Normal::returnCode(Normal::SUC, "处理完成");
    }

    /**
     * 订单售后
     * @param array $param
     * @return array
     */
    public function orderAfterSale($param = []) {
        return $this->callSdkApi(ShopjdkeplerClient::class, $param['apiBody'])->cancelOrder($param);
    }

    /**
     * 商品列表查询接口
     * @param array $param
     * @return array
     */
    public function queryGoodsList($param = []) {
        return Normal::returnCode(Normal::SUC, "处理完成");
        // $res = $this->callSdkApi(ShopjdkeplerClient::class, $param['apiBody'])->{__FUNCTION__}($param['queryBody']);
        // if ($res['code'] != Normal::SUC) {
        //     return $res;
        // }
        // return Normal::returnCode(Normal::SUC, "获取成功", [
        //     'total'   => $res['data']['total'],
        //     'list'    => $res['data']['data'],
        //     'hasPage' => $res['data']['hasPage'] ?? 1
        // ]);
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress($param = []) {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id' => $orderID, 'company_id' => $queryBody['supplierID']]);
        if (empty($orderInfo)) {
            return Normal::returnCode(Normal::FAIL, "订单信息不存在");
        }
        $res = $this->callSdkApi(ShopjdkeplerClient::class, $apiBody)->{__FUNCTION__}($orderInfo);
        if ($res['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $res['msg']);
        }
        $expressInfo = $res['data'];
        if (!isset($expressInfo['expressNo']) || empty($expressInfo['expressNo'])) {
            return Normal::returnCode(Normal::FAIL, "获取expressNo失败");
        }
        // if (!isset($expressInfo['expressName']) || empty($expressInfo['expressName'])) {
        //     return Normal::returnCode(Normal::FAIL, "获取expressName失败");
        // }
        $expressName = $expressInfo['expressName'];
        $expressNo   = $expressInfo['expressNo'];
        //拿到快递100里面去查询快递公司名称
        if(empty($expressName) && empty($orderInfo['express_name'])){
            $queryConfig = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('kuaidi100');
            if(!$queryConfig){
                return Normal::returnCode(Normal::FAIL, "获取快递100配置失败");
            }
            $queryExpressNameRes = $this->callSdkApi(ShopjdkeplerClient::class, $apiBody)->queryExpressName($expressNo,$queryConfig);
            if ($queryExpressNameRes['code'] != Normal::SUC) {
                return Normal::returnCode(Normal::FAIL, '快递100查询失败' . $res['msg']);
            }
            $expressNameArr = $queryExpressNameRes['data'];
            $expressName = $expressNameArr['expressName'];
        }
        return Normal::returnCode(Normal::SUC, "已发货", [
            'expressInfo' => [
                'express_name' => mb_strtoupper($expressName, 'utf-8'),
                'express_sn'   => $expressNo,
            ],
        ]);
    }
}